package com.i9he.ping.service.impl;

import static com.i9he.ping.utils.ConfigUtils.configuration;

import org.apache.log4j.Logger;

import com.i9he.ping.model.IPStatus;
import com.i9he.ping.service.IPStrategyHandler;
import com.i9he.ping.service.Strategy;
import com.i9he.ping.utils.LoggerUtils;
public class StrategyImpl implements Strategy {

	private final Logger logger;
	private IPStrategyHandler ipStrategyHandler;

	public StrategyImpl(IPStrategyHandler ipStrategyHandler) {
		this.ipStrategyHandler = ipStrategyHandler;
		logger = LoggerUtils.getLoggerByName("monitor", true);
	}

	@Override
	public void analysisStatus(IPStatus ip,int errorCount) {
		int failure = configuration.getInt("ping.failure.count");//超时次数 4
		int reconnection = configuration.getInt("ping.reconnect.count");//连接成功次数判断是否成功5
		int pingCount = configuration.getInt("ping.average.count", 0);
		//TODO 加ping成功监测 的平均值   有必要 使用 boolean  作标记
		
		 if(ip.getSuccessCount() == (pingCount + 2 - errorCount)){
			 if(errorCount < failure){
				 ip.setDelay(true);
				 ip.setSuccessCount(0);
				 logger.info(ip.getIp() + ": 网络延迟过大");
				 this.delay(ip);//发送网络延迟邮件
				 ip.setDelay(false);
			 }
		 }
		
		if (ip.getErrorCount() == 0) {
			if (ip.isBroken() && ip.getSuccessCount() >= reconnection) {
				ip.setBroken(false);
				logger.info(ip.getIp() + ": 恢复网络");
				this.reconnect(ip);
			}
		} else if (ip.getErrorCount() < failure) {
			logger.warn(ip.getIp() + ": 出现网络异常");
		} else {
			if (!ip.isBroken()) {
				logger.warn(ip.getIp() + ": 网络中断");
				ip.setBroken(true);
				this.broken(ip); //把ip放到 邮件线程里面，这样邮件线程接到ip之后，就开始对这个ip做处理并发送邮件//邮件线程有一直在运行，只是一开始没有ip给这条线程
//				ip.setErrorCount(0);  //允许重连ip				
			}
		}
	}

	@Override
	public void reconnect(IPStatus ip) {
		ipStrategyHandler.reconnect(ip);//传递重连ip
	}

	@Override
	public void broken(IPStatus ip) {
		ipStrategyHandler.broken(ip); //传递中断ip
	}

	@Override
	public void delay(IPStatus ip) {
		ipStrategyHandler.delay(ip);
	}
}
